// pages/your-page/your-page.js
let loadTimer = null;

Component({
  data: {
    status: 0, //0加载中 1加载成功 2加载失败
    isShow: false
  },
  properties: {
    //显示类型
    mode: {
      type: String,
      value: "aspectFill"
    },
    //图片圆角 必须带尺寸单位
    borderRadius: {
      type: String,
      value: "0"
    },
    //图片宽度
    width: {
      type: String,
      value: "100%"
    },
    //图片高度
    height: {
      type: String,
      value: "100%"
    },
    //图片链接
    src: {
      type: String,
      value: ""
    },
    //当图片加载过快(存在缓存)至少显示多少秒加载动画
    minTimeOut: {
      type: String || Number,
      value: "300"
    },
    //当图片到屏幕哪个位置的时候开始加载 单位px 可以是负数
    showDistance: {
      type: Object,
      value: {
        bottom: 0
      }
    },
    //过渡效果  linear / ease / ease-in / ease-out / ease-in-out
    effect: {
      type: String,
      value: "linear"
    },
    //图片加载成功后的过渡时间 单位毫秒
    duration: {
      type: String || Number,
      value: "300"
    },
    //加载中图片
    loadSrc: {
      type: String,
      value: '/static/loading.png'
    },
    //加载失败图片
    errorSrc: {
      type: String,
      value: '/static/loading.png'
    }
  },
  observers: {
    'src': function (newSrc) {
      if (!this.data.isShow) return;
      this.setData({
        status: 0,
        isShow: false
      });
      setTimeout(() => {
        this.setData({
          status: 1
        });
      });
    }
  },
  lifetimes: {
    destroyed() {
      //页面销毁取消监听
      this.triggerEvent('destroyed');
    }
  },
  methods: {
    load() {
      if (this.data.minTimeOut == 0) {
        this.setData({
          isShow: true
        });
      } else {
        let newTimer = new Date().getTime() - loadTimer;
        if (newTimer < this.data.minTimeOut) {
          setTimeout(() => {
            this.setData({
              isShow: true
            });
          }, this.data.minTimeOut - newTimer);
        } else {
          this.setData({
            isShow: true
          });
        }
      }

      setTimeout(() => {
        this.triggerEvent('showSuccess');
      }, this.data.duration);
    },
    error() {
      this.setData({
        status: 2,
        isShow: true
      });
    },
    init() {
      let intersectionObserver = wx.createIntersectionObserver(this);
      let load = false;

      //当图片加载完的时候取消监听
      // this.once('destroyed', () => {
      //   intersectionObserver.disconnect();
      // });

      intersectionObserver.relativeToViewport(this.data.showDistance).observe('.muqain-load', (res) => {
        if (!load && res.intersectionRatio == 0) {
          load = true;
          return;
        }
        this.triggerEvent('show');
        load = true;
        this.setData({
          status: 1
        });
        loadTimer = new Date().getTime();
        intersectionObserver.disconnect();
      });
    }
  }
});